package com.example.demo3.interceptor;


import com.example.demo3.util.RedisUtil;
import com.example.demo3.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");//取token字符串
        String uri = request.getRequestURI();//获取url,如果是login或者register直接放行
//"OPTIONS".equals(request.getMethod():测试连接
        if("/user/login".equals(uri)||"OPTIONS".equals(request.getMethod())){
            return  true;//放行,不拦截
        }else {
            //判断是否登录
            if(token==null){
                System.out.println("拦截");
                return false;//拦截
            }
            //token认证
            TokenUtil tokenUtil = new TokenUtil();
            //token字符串是否正确+redis中token时间是否到期
            if(tokenUtil.verifyToken(token)&&redisUtil.hasKey(token)){
                return true;
            }
        }
        //认证失败
        System.out.println("拦截");
        //response.getWriter().println(new Gson().toJson(new Result(300,"token有误",null)));
        return false;
    }


}
